package view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

import controller.*;

public class SwingView implements IView {

	private Controller controller;
	private JFrame frame;
	private JTextField textField;
	private JTextArea textArea;
	private String input;

	public SwingView(Controller c) {
		setController(c);
		c.setView(this);
		textField = new JTextField();
		JButton btnSearch = new JButton("Search");
		textField.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				doSearch();
			}
		});
		btnSearch.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				doSearch();
			}
		});
		textArea = new JTextArea(5, 20);
		JScrollPane scrollPane = new JScrollPane(textArea);
		textArea.setEditable(false);

		JPanel content = new JPanel();
		content.setLayout(new BorderLayout());
		content.add(textField, BorderLayout.NORTH);
		content.add(btnSearch, BorderLayout.EAST);
		content.add(scrollPane, BorderLayout.CENTER);

		frame = new JFrame();
		frame.setPreferredSize(new Dimension(800, 600));
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setTitle("Really Nice Search Engine");
		frame.setContentPane(content);
		frame.pack();

		frame.setVisible(true);
		textArea.append(controller.toString());
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see view.IView#doSearch()
	 */
	@Override
	public void doSearch() {
		input = textField.getText();
		textField.setText("");
		textField.requestFocus();
		controller.doSearch(input);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see view.IView#setController(controller.Controller)
	 */
	@Override
	public void setController(Controller ctrl) {
		controller = ctrl;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see view.IView#showResult(java.lang.String[])
	 */
	@Override
	public void showResult(String[] result) {
		if (result == null || result.length == 0) {
			textArea.append("No match found: " + input + "\n\n");
		} else {
			textArea.append("Results for search: " + input + "\n");
			for (String s : result) {
				textArea.append(s + "\n");
			}
			textArea.append("\n");
		}
	}

	@Override
	public String toString() {
		return this.getClass().getName();
	}

}
